import React from 'react';
import {
  StyleSheet,
  Text,
  View,
  Button,
  Image,
  TouchableOpacity,
  FlatList,
  ScrollView,
} from 'react-native';
import {
  ActivityIndicator,
  Toast,
  Modal,
} from 'antd-mobile-rn';
import { connect } from 'react-redux';
import _ from 'lodash';

import { scaleSize } from '../../utils/screen';
import FontText from '../components/FontText';
import { i18n } from '../../i18n';

import * as tableActions from './actions/tableActions';
import AddTableActionBar from '../components/AddTableActionBar';
import TableWithSeats from '../components/TableWithSeats';
import LayoutModal from '../components/modal/LayoutModal';
import TableModal from '../components/modal/TableModal';

class AddTable extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedLayout: {},
      selectedDesk: {},
    };
  }

  componentDidMount() {
    this.props.getLayoutList();
  }

  goBack() {
    this.setState({
      selectedLayout: {},
      selectedDesk: {},
    });

    this.props.navigation.goBack();
  }

  renderBackButton() {
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => this.goBack()}
        style={styles.backButton}
      >
        <Image
          style={styles.backButtonIcon}
          source={require('../../access/imgs/arrow_left.png')}
        />
        <FontText
          style={styles.backButtonText}
          font={'book'}
        >
          {i18n.t('btns.back')}
        </FontText>
      </TouchableOpacity>
    );
  }

  createLayout() {
    this.props.createLayout();
  }

  layoutModalSave(layout) {
    const { name } = layout;
    if (name.length === 0) {
      return Toast.info(i18n.t('store.table.modal.layout.required.name'), 3, null, false)
    }

    this.props.saveLayout(layout);
  }

  layoutModalCance() {
    this.props.cancelEditLayout();
  }

  editLayout() {
    const { selectedLayout } = this.state;

    this.props.editlayout(selectedLayout);
  }

  deleteLayout(layoutId) {
    this.props.deleteLayout(
      layoutId,
      () => {
        this.setState({
          selectedLayout: {},
        });
      },
    );
  }

  deleteLayoutConfirm() {
    const { selectedLayout } = this.state;

    Modal.alert('', i18n.t('store.table.alert.deletelayoutmessage'), [
      { text: i18n.t('btns.cancel'), onPress: () => {}, style: 'cancel' },
      { text: i18n.t('btns.okText'), onPress: () => this.deleteLayout(selectedLayout.server_layout_id) },
    ]);
  }

  saveLayout() {
    this.setState({
      selectedLayout: {},
      selectedDesk: {},
    });
  }

  addTable(layoutId) {
    this.props.addDesk(layoutId);
  }

  editTable(desk) {
    const { selectedDesk } = this.state;

    this.props.editDesk(selectedDesk);
  }

  deleteTable(deskId) {
    this.props.deleteDesk(
      deskId,
      () => {
        this.setState({
          selectedDesk: {},
        });
      },
    );
  }

  deleteTableConfirm() {
    const { selectedDesk } = this.state;

    Modal.alert('', i18n.t('store.table.alert.deletetablemessage'), [
      { text: i18n.t('btns.cancel'), onPress: () => {}, style: 'cancel' },
      { text: i18n.t('btns.okText'), onPress: () => this.deleteTable(selectedDesk.server_desk_id) },
    ]);
  }

  tableModalSave(desk, seats) {
    const { name } = desk;
    if (name.length === 0) {
      return Toast.info(i18n.t('store.table.modal.table.required.name'), 3, null, false)
    }

    if (seats.length === 0) {
      return Toast.info(i18n.t('store.table.modal.table.required.seats'), 3, null, false)
    }

    const { selectedLayout } = this.state;
    const { table } = this.props;

    this.props.saveDesk(
      selectedLayout.server_layout_id,
      table.desks,
      desk,
      (deskId) => {
        this.props.saveSeats(
          deskId,
          seats,
          () => {
            this.setState({
              selectedDesk: {},
            });
          },
        );
      },
    );
  }

  tableModalCancel() {
    this.props.cancelEditDesk();
  }

  _createHeaderLeftActions() {
    let leftActions = [];
    const { selectedLayout } = this.state;

    if (_.isEmpty(selectedLayout)) {
      leftActions.push({
        label: i18n.t('store.table.addtableview.createlayout'),
        action: () => this.createLayout(),
      });
    } else {
      const { selectedDesk } = this.state;

      leftActions.push({
        label: i18n.t('store.table.addtableview.editlayout'),
        action: () => this.editLayout(),
      });

      if (_.isEmpty(selectedDesk)) {
        leftActions.push({
          label: i18n.t('store.table.addtableview.addtable'),
          action: () => this.addTable(selectedLayout.server_layout_id),
        });
      } else {
        leftActions.push({
          label: i18n.t('store.table.addtableview.edittable'),
          action: () => this.editTable(selectedDesk),
        });
      }
    }

    return leftActions;
  }

  _createHeaderRightActions() {
    let rightActions = [];
    const { selectedLayout } = this.state;

    if (!_.isEmpty(selectedLayout)) {
      const { selectedDesk } = this.state;

      if (!_.isEmpty(selectedDesk)) {
        rightActions.push({
          label: i18n.t('store.table.addtableview.deletetable'),
          action: () => this.deleteTableConfirm(),
          style: { backgroundColor: '#fff' },
        });
      }

      rightActions.push({
        label: i18n.t('store.table.addtableview.deletelayout'),
        action: () => this.deleteLayoutConfirm(),
        style: { backgroundColor: '#fff' },
      });
      rightActions.push({
        label: i18n.t('store.table.addtableview.savelayout'),
        action: () => this.saveLayout(),
        style: { backgroundColor: '#fd265d', color: '#fff' },
      });
    }

    return rightActions;
  }

  renderHeader() {
    const leftActions = this._createHeaderLeftActions();
    const rightActions = this._createHeaderRightActions();

    return (
      <View style={styles.headerContainer}>
        {this.renderBackButton()}
        <AddTableActionBar
          leftActions={leftActions}
          rightActions={rightActions}
        />
      </View>
    );
  }

  selectLayout(layout) {
    const { selectedLayout } = this.state;

    if (selectedLayout.server_layout_id !== layout.server_layout_id) {
      this.setState({
        selectedLayout: layout,
        selectedDesk: {},
      });

      this.props.getDeskList(layout.server_layout_id);
    }
  }

  renderLayoutItem({ item: layout }) {
    const { selectedLayout } = this.state;
    let isSelected = false;
    if (!_.isEmpty(selectedLayout) &&
        selectedLayout.server_layout_id === layout.server_layout_id) {
      isSelected = true;
    }

    return (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => this.selectLayout(layout)}
        style={styles.layoutItem}
      >
        <FontText
          style={
            isSelected ?
            [styles.layoutItemName, {color: '#fff'}]:
            styles.layoutItemName
          }
          font={'book'}
        >
          { layout.name }
        </FontText>
      </TouchableOpacity>
    );
  }

  renderLayoutList() {
    const { table } = this.props;

    return (
      <FlatList
        data={table.layouts}
        extraData={this.state}
        renderItem={(item, index) => this.renderLayoutItem(item, index)}
        keyExtractor={(item, index) => `${index}`}
      />
    );
  }

  selectTable(selected, desk) {
    let selectedDesk = desk;

    if (!selected) {
      selectedDesk = {};
    }

    this.setState({
      selectedDesk: selectedDesk,
    });
  }

  renderTables() {
    const { table } = this.props;
    const { selectedLayout, selectedDesk } = this.state;

    if (!_.isEmpty(selectedLayout)) {
      return table.desks.map((desk, index) => {
        const defaultValue = !_.isEmpty(selectedDesk) && desk.server_desk_id === selectedDesk.server_desk_id;
        return (
          <TableWithSeats
            table={desk}
            seats={desk.seats}
            key={index}
            defaultValue={defaultValue}
            onSelectionChange={(selected) => this.selectTable(selected, desk)}
          />
        );
      });
    }

    return null;
  }

  renderContent() {
    return (
      <View style={styles.contentContainer}>
        <View style={styles.layoutListContainer}>
          {this.renderLayoutList()}
        </View>
        <ScrollView
          style={styles.tableGridScrollview}
          bounces={false}
        >
          <View style={styles.tableGridContainer}>
            {this.renderTables()}
          </View>
        </ScrollView>
      </View>
    );
  }

  renderActivityIndicator() {
    const { table } = this.props;
    const needIndicator = table.loading | table.saving | table.deleting;
    let indicatorText = '';

    if (table.loading) {
      indicatorText = i18n.t('store.table.indicator.loading');
    } else if (table.saving) {
      indicatorText = i18n.t('store.table.indicator.saving');
    } else if (table.deleting) {
      indicatorText = i18n.t('store.table.indicator.deleting');
    }

    return (
      <ActivityIndicator
        animating={needIndicator}
        toast
        size='small'
        text={indicatorText}
      />
    );
  }

  render() {
    const { table } = this.props;
    const showLayoutModal = !_.isEmpty(table.editingLayout);
    const showTableModal = !_.isEmpty(table.editingDesk);

    return (
      <View style={styles.addTableView}>
        {this.renderHeader()}
        {this.renderContent()}
        {this.renderActivityIndicator()}
        <LayoutModal
          show={showLayoutModal}
          layout={table.editingLayout}
          onSave={(layout) => this.layoutModalSave(layout)}
          onCancel={() => this.layoutModalCance()}
        />
        <TableModal
          show={showTableModal}
          desk={table.editingDesk}
          onSave={(desk, seats) => this.tableModalSave(desk, seats)}
          onCancel={() => this.tableModalCancel()}
        />
      </View>
    );
  }
};

/* StyleSheet =============================================================== */

const styles = StyleSheet.create({
  addTableView: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  headerContainer: {
    backgroundColor: '#090d17',
    height: scaleSize(120),
    flexDirection: 'row',
  },
  backButton: {
    flexDirection: 'row',
    alignItems: 'center',
    height: scaleSize(120),
    width: scaleSize(230),
    paddingLeft: scaleSize(30),
  },
  backButtonIcon: {
    width: scaleSize(17),
    height: scaleSize(30),
  },
  backButtonText: {
    fontSize: scaleSize(27),
    color: '#9b9b9b',
    paddingLeft: scaleSize(18),
  },
  contentContainer: {
    flex: 1,
    flexDirection: 'row',
  },
  layoutListContainer: {
    width: scaleSize(230),
    backgroundColor: '#151c2e',
  },
  tableGridScrollview: {
    backgroundColor: '#090d17',
  },
  tableGridContainer: {
    flex: 1,
    borderTopColor: '#151c2e',
    borderTopWidth: scaleSize(1),
    flexWrap: 'wrap',
    flexDirection: 'row',
  },
  layoutItem: {
    flexDirection: 'row',
    height: scaleSize(100),
    justifyContent: 'center',
    alignItems: 'center',
  },
  layoutItemName: {
    color: '#9b9b9b',
    fontSize: scaleSize(27),
  },
});

function mapStateToProps({ table }) {
  return { table };
}

export default connect(mapStateToProps, tableActions)(AddTable);
